package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.*;
import com.dropdb.demo.bean.vo.*;
import com.dropdb.demo.mapper.*;
import com.dropdb.demo.service.WxHomeAndGoodsService;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.util.*;

/**
 * @author Alone
 * @version 1.0
 * @date 2020/6/30 15:06
 */
@Service
public class WxHomeAndGoodsServiceImpl implements WxHomeAndGoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    AdMapper adMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    GrouponMapper grouponMapper;
    @Autowired
    TopicMapper topicMapper;
    @Autowired
    GoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    CouponMultiTableMapper couponMultiTableMapper;
    @Autowired
    FootprintMapper footprintMapper;

    private static final String DESC = "update_time desc";
    //待整合shiro
    private Integer userId=0;
    @Override
    public Map<String, Object> queryUser(String username) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        User user = users.size() == 1 ? users.get(0) : null;
        HashMap<String, Object> vo = new HashMap<>();
        String token = (String) SecurityUtils.getSubject().getSession().getId();
        vo.put("token", token);
        vo.put("tokenExpire", new Date(System.currentTimeMillis()));
        HashMap userInfo = new HashMap<String, String>();
        userInfo.put("avatarUrl", user.getAvatar());
        userInfo.put("nickName", user.getNickname());
        this.userId=user.getId();
        vo.put("userInfo", userInfo);
        return vo;
    }

    @Override
    public Integer countTotalGoods() {
        GoodsExample goodsExample = new GoodsExample();
        int l = (int) goodsMapper.countByExample(goodsExample);
        return l;
    }

    @Override
    public Map<String, Object> goodsList(Integer categoryId, Integer page, Integer size, String sort, String order, String keyword, Integer brandId, Boolean isHot, Boolean isNew) {
        Map<String, Object> vo = new HashMap<>();
        //如果有关键词还要加入搜索历史
        if (keyword != null && !"".equals(keyword)) {
            //同一用户最好保持记录不重复
            SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
            SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andKeywordEqualTo(keyword);
            List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);
            SearchHistory searchHistory = searchHistories.size()>=1?searchHistories.get(0):new SearchHistory();
            if(searchHistories.size()==0){
                searchHistory.setAddTime(new Date(System.currentTimeMillis()));
            }
            searchHistory.setUpdateTime(new Date(System.currentTimeMillis()));
            searchHistory.setDeleted(false);
            searchHistory.setKeyword(keyword);
            searchHistory.setFrom("wx");
            //criteria.andUpdateTimeEqualTo(new Date(System.currentTimeMillis()));
            criteria.andKeywordEqualTo(keyword);
            //此处待整合shiro
            searchHistory.setUserId(userId);
            if(searchHistories.size()>=1){
                searchHistoryMapper.updateByExampleSelective(searchHistory,searchHistoryExample);
            }else{
                searchHistoryMapper.insert(searchHistory);
            }

        }
        if (categoryId == null && brandId != null) {
            Brand brand = brandMapper.selectByPrimaryKey(brandId);
            GoodsExample example = new GoodsExample();
            example.createCriteria().andBrandIdEqualTo(brandId).andDeletedEqualTo(false);
            List<Goods> goods = goodsMapper.selectByExample(example);
            int count = (int) goodsMapper.countByExample(example);
            vo.put("goodsList", goods);
            vo.put("count", count);
            ArrayList<Category> categories = new ArrayList<>();
            for (Goods good : goods) {
                /*CategoryExample categoryExample = new CategoryExample();
                categoryExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(good.getId());*/

                //此处过滤相同的category
                boolean flag = false;
                for (Category category : categories) {
                    if (category.getId().equals(good.getCategoryId())) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    continue;
                }
                Category ca = categoryMapper.selectByPrimaryKey(good.getCategoryId());
                categories.add(ca);
            }
            vo.put("brand",brand);
            vo.put("filterCategoryList", categories);
            //vo.put("filterCategoryList",categories);
            return vo;
        }
        if (categoryId == 0) {
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria = goodsExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            if (keyword != null && !"".equals(keyword)) {
                criteria.andNameLike("%" + keyword + "%");
            }
            if (isHot != null) {
                criteria.andIsHotEqualTo(isHot);
            }
            if (isNew != null) {
                criteria.andIsNewEqualTo(isNew);
            }
            goodsExample.setOrderByClause(sort + " " + order);
            PageHelper.startPage(page, size);
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            int count = (int) goodsMapper.countByExample(goodsExample);
            vo.put("goodsList", goods);
            vo.put("count", count);
            ArrayList<Category> categories = new ArrayList<>();
            for (Goods good : goods) {
                /*CategoryExample categoryExample = new CategoryExample();
                categoryExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(good.getId());*/

                //此处过滤相同的category
                boolean flag = false;
                for (Category category : categories) {
                    if (category.getId().equals(good.getCategoryId())) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    continue;
                }
                Category ca = categoryMapper.selectByPrimaryKey(good.getCategoryId());
                categories.add(ca);
            }
            vo.put("filterCategoryList", categories);
        } else {
            GoodsExample goodsExample = new GoodsExample();
            GoodsExample.Criteria criteria = goodsExample.createCriteria();
            criteria.andDeletedEqualTo(false).andCategoryIdEqualTo(categoryId);
            if (isHot != null) {
                criteria.andIsHotEqualTo(isHot);
            }
            if (isNew != null) {
                criteria.andIsNewEqualTo(isNew);
            }
            if (sort != null && !"".equals(sort) && order != null){
                goodsExample.setOrderByClause(sort + " " + order);
            }
            PageHelper.startPage(page, size);
            List<Goods> goods = goodsMapper.selectByExample(goodsExample);
            int count = (int) goodsMapper.countByExample(goodsExample);
            CategoryExample categoryExample = new CategoryExample();
            categoryExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(categoryId);
            List<Category> categories = categoryMapper.selectByExample(categoryExample);
            vo.put("goodsList", goods);
            vo.put("count", count);
            vo.put("filterCategoryList", categories);
        }


        /*vo.put("count",count);*/
        /*vo.put("goodsList",goods);*/
        /*vo.put("filterCategoryList",categoryList);*/
        return vo;
    }

    @Override
    public Map<String, Object> goodsCategory(Integer id) {
        HashMap<String, Object> vo = new HashMap<>();
        //parentCategory
        Category parent = categoryMapper.selectByPrimaryKey(id);
        Category current = parent;
        //id为二级类目
        boolean flag = false;
        if (parent.getPid() != 0) {
            parent = categoryMapper.selectByPrimaryKey(parent.getPid());
            flag = true;
        }
        vo.put("parentCategory", parent);
        CategoryExample example = new CategoryExample();
        example.createCriteria().andDeletedEqualTo(false).andPidEqualTo(parent.getId());
        //brotherCategory
        List<Category> brothers = categoryMapper.selectByExample(example);
        vo.put("brotherCategory", brothers);
        if (brothers.size() != 0) {
            //当id是二级类目时 直接将查询的put 否则将brother第一个put
            if (flag) {
                vo.put("currentCategory", current);
            } else {
                vo.put("currentCategory", brothers.get(0));
            }
        }
        return vo;
    }

    @Override
    public Map<String, Map<String, Integer>> userIndex() {
        HashMap<String, Map<String, Integer>> vo = new HashMap<>();
        HashMap<String, Integer> map = new HashMap<>();
        OrderExample uncomment = new OrderExample();
        uncomment.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 401).andCommentsNotEqualTo((short)0);
        int uncommentNum = (int) orderMapper.countByExample(uncomment);

        OrderExample unpaid = new OrderExample();
        unpaid.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 101);
        int unpaidNum = (int) orderMapper.countByExample(unpaid);

        OrderExample unrecv = new OrderExample();
        unrecv.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 301);
        int unrecvNum = (int) orderMapper.countByExample(unrecv);

        OrderExample unship = new OrderExample();
        unship.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andOrderStatusEqualTo((short) 201);
        int unshipNum = (int) orderMapper.countByExample(unship);

        map.put("uncomment", uncommentNum);
        map.put("unpaid", unpaidNum);
        map.put("unrecv", unrecvNum);
        map.put("unship", unshipNum);

        vo.put("order", map);
        return vo;
    }

    @Override
    public WxGoodsDetailVO goodsDetail(Integer id) {
        WxGoodsDetailVO vo = new WxGoodsDetailVO();
        //FootprintExample footprintExample = new FootprintExample();
        Footprint footprint = new Footprint();
        footprint.setAddTime(new Date(System.currentTimeMillis()));
        footprint.setUpdateTime(new Date(System.currentTimeMillis()));
        footprint.setUserId(userId);
        footprint.setGoodsId(id);
        footprint.setDeleted(false);
        footprintMapper.insert(footprint);
        /*
        * List<GoodsAttribute> attribute;
        Brand brand;
        Map<String,Object> comment;
        List<Groupon> groupon;
        Goods info;
        List<Issue> issue;
        List<GoodsProduct> productList;
        List<Map<String,Object>> specificationList;
        * shareImage
        Integer userHasCollect;*/
        GoodsAttributeExample goodsAttributeExample = new GoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<GoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        Goods goods = goodsMapper.selectByPrimaryKey(id);
        WxGoodsVO wxGoodsVO = new WxGoodsVO();
        wxGoodsVO.setAddTime(goods.getAddTime());
        wxGoodsVO.setBrandId(goods.getBrandId());
        wxGoodsVO.setBrief(goods.getBrief());
        wxGoodsVO.setCategoryId(goods.getCategoryId());
        wxGoodsVO.setCounterPrice(Double.parseDouble(goods.getCounterPrice()));
        wxGoodsVO.setDeleted(goods.getDeleted());
        wxGoodsVO.setGallery(goods.getGallery());
        wxGoodsVO.setGoodsSn(goods.getGoodsSn());
        wxGoodsVO.setId(goods.getId());
        wxGoodsVO.setIsHot(goods.getIsHot());
        wxGoodsVO.setIsNew(goods.getIsNew());
        wxGoodsVO.setIsOnSale(goods.getIsOnSale());
        wxGoodsVO.setKeywords(goods.getKeywords());
        wxGoodsVO.setName(goods.getName());
        wxGoodsVO.setPicUrl(goods.getPicUrl());
        wxGoodsVO.setRetailPrice(Double.parseDouble(goods.getRetailPrice()));
        wxGoodsVO.setShareUrl(goods.getShareUrl());
        wxGoodsVO.setSortOrder(goods.getSortOrder());
        wxGoodsVO.setUnit(goods.getUnit());
        wxGoodsVO.setUpdateTime(goods.getUpdateTime());

        Brand brand = brandMapper.selectByPrimaryKey(goods.getBrandId());


         /*
         参考
        * for (LitemallComment comment : comments) {
				Map<String, Object> c = new HashMap<>();
				c.put("id", comment.getId());
				c.put("addTime", comment.getAddTime());
				c.put("content", comment.getContent());
				c.put("adminContent", comment.getAdminContent());
				LitemallUser user = userService.findById(comment.getUserId());
				c.put("nickname", user == null ? "" : user.getNickname());
				c.put("avatar", user == null ? "" : user.getAvatar());
				c.put("picList", comment.getPicUrls());
				commentsVo.add(c);
			}
        * */
        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(id);
        commentExample.setOrderByClause(DESC);
        //要善用map 和 list
        List<Comment> comments = commentMapper.selectByExample(commentExample);
        int count = (int) commentMapper.countByExample(commentExample);
        ArrayList<Map> maps = new ArrayList<>();
        int countComments = 0;
        for (Comment comment : comments) {
            HashMap<String, Object> c = new HashMap<>();
            c.put("id", comment.getId());
            c.put("addTime", comment.getAddTime());
            c.put("content", comment.getContent());
            User user = userMapper.selectByPrimaryKey(comment.getUserId());
            c.put("nickname", user == null ? "" : user.getNickname());
            c.put("avatar", user == null ? "" : user.getAvatar());
            c.put("picList", comment.getPicUrls());
            maps.add(c);
            countComments++;
            if (countComments == 2) {
                break;
            }
        }
        HashMap<String, Object> comment = new HashMap<>();
        comment.put("count", count);
        comment.put("data", maps);

        IssueExample issueExample = new IssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        List<Issue> issues = issueMapper.selectByExample(issueExample);

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        List<WxProductVO> product = new ArrayList<>();
        for (GoodsProduct goodsProduct : goodsProducts) {
            WxProductVO wxProductVO = new WxProductVO();
            wxProductVO.setAddTime(goodsProduct.getAddTime());
            wxProductVO.setDeleted(goodsProduct.getDeleted());
            wxProductVO.setGoodsId(goodsProduct.getGoodsId());
            wxProductVO.setId(goodsProduct.getId());
            wxProductVO.setNumber(Integer.parseInt(goodsProduct.getNumber()));
            wxProductVO.setPrice(Double.parseDouble(goodsProduct.getPrice()));
            wxProductVO.setSpecifications(goodsProduct.getSpecifications());
            wxProductVO.setUpdateTime(goodsProduct.getUpdateTime());
            wxProductVO.setUrl(goodsProduct.getUrl());
            product.add(wxProductVO);
        }



        GoodsSpecificationExample goodsSpecificationExample = new GoodsSpecificationExample();
        //此处需要group by specification
        goodsSpecificationExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(id);
        List<GoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        //返回值为list
        //list 中的map 存储name--specification
        //               valueList--specifications
        ArrayList<Map<String, Object>> spe = new ArrayList<>();

        label:
        for (int i = 0; i < goodsSpecifications.size(); i++) {
            GoodsSpecification goodsSpecification = goodsSpecifications.get(i);
            boolean flag = false;
            for (Map<String, Object> spec : spe) {
                if (goodsSpecification.getSpecification().equals(spec.get("name"))) {
                    ArrayList list1 = (ArrayList) spec.get("valueList");
                    list1.add(goodsSpecification);
                    flag = true;
                    break;
                }
            }
            //存在相同 name  直接跳过下面的新增环节
            if (flag) {
                continue;
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", goodsSpecification.getSpecification());
            ArrayList<GoodsSpecification> list2 = new ArrayList<>();
            /*for(int j=i;j<goodsSpecifications.size();j++){
                if(goodsSpecifications.get(j).getSpecification().equals(goodsSpecification.getSpecification())){
                    list1.add(goodsSpecifications.get(j));
                }
            }*/
            list2.add(goodsSpecification);
            map.put("valueList", list2);
            spe.add(map);
        }

        //查询是否收藏
        //userId 需要shiro整合
        CollectExample collectExample = new CollectExample();
        collectExample.createCriteria().andDeletedEqualTo(false).andValueIdEqualTo(id).andUserIdEqualTo(userId);
        List<Collect> collects = collectMapper.selectByExample(collectExample);
        boolean collect = true;
        if (collects == null || collects.size() == 0) {
            collect = false;
        }


        vo.setAttribute(goodsAttributes);
        vo.setBrand(brand);
        vo.setComment(comment);
        vo.setInfo(goods);
        vo.setIssue(issues);
        vo.setProductList(product);
        vo.setSpecificationList(spe);
        vo.setUserHasCollect(collect);
        vo.setGroupon(new ArrayList<Groupon>());
        return vo;
    }

    @Override
    public Map<String, Object> goodsRelated(Integer id) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andCategoryIdEqualTo(goods.getCategoryId()).andDeletedEqualTo(false);
        PageHelper.startPage(1, 4);
        List<Goods> list = goodsMapper.selectByExample(goodsExample);
        HashMap<String, Object> vo = new HashMap<>();
        vo.put("goodsList", list);
        return vo;
    }

    @Override
    public WxHomeIndexVO queryHomePage() {
        AdExample adExample = new AdExample();
        adExample.createCriteria().andDeletedEqualTo(false);
        adExample.setOrderByClause(DESC);
        //PageHelper.startPage(1,2);
        List<Ad> ads = adMapper.selectByExample(adExample);

        BrandExample brandExample = new BrandExample();
        brandExample.createCriteria().andDeletedEqualTo(false);
        brandExample.setOrderByClause(DESC);
        PageHelper.startPage(1, 4);
        List<Brand> brands = brandMapper.selectByExample(brandExample);

        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(0);
        //categoryExample.setOrderByClause(DESC);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);

        //最好使用连表查询
        List<WxCategoryListVO> list = new ArrayList<WxCategoryListVO>();
        int count = 0;
        for (Category category : categories) {
            WxCategoryListVO wxCategoryListVO = new WxCategoryListVO();
            wxCategoryListVO.setId(category.getId());
            wxCategoryListVO.setName(category.getName());

            //先将所有二级目录查出
            CategoryExample secondCategory = new CategoryExample();
            secondCategory.createCriteria().andDeletedEqualTo(false).andPidEqualTo(category.getId());
            List<Category> categoriesSecond = categoryMapper.selectByExample(secondCategory);
            ArrayList<Integer> integers = new ArrayList<>();
            for (Category category1 : categoriesSecond) {
                integers.add(category1.getId());
            }

            GoodsExample example = new GoodsExample();
            if (integers.size() == 0) {
                continue;
            } else {
                example.createCriteria().andCategoryIdIn(integers).andDeletedEqualTo(false);
            }
            example.setOrderByClause(DESC);
            PageHelper.startPage(1, 4);
            List<Goods> goods = goodsMapper.selectByExample(example);

            wxCategoryListVO.setGoodsList(goods);
            list.add(wxCategoryListVO);
            count++;
            if (count == 4) {
                break;
            }
        }

        /*CouponExample couponExample = new CouponExample();
        couponExample.createCriteria().andDeletedEqualTo(false);
        couponExample.setOrderByClause(DESC);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);*/
        List<CouponListElementtData> coupons = couponMultiTableMapper.list(userId);

        GoodsExample hotGoodsExample = new GoodsExample();
        hotGoodsExample.setOrderByClause(DESC);
        hotGoodsExample.createCriteria().andIsHotEqualTo(true).andDeletedEqualTo(false);
        PageHelper.startPage(1, 4);
        List<Goods> hots = goodsMapper.selectByExample(hotGoodsExample);

        GoodsExample newGoodsExample = new GoodsExample();
        newGoodsExample.createCriteria().andDeletedEqualTo(false).andIsNewEqualTo(true);
        newGoodsExample.setOrderByClause(DESC);
        PageHelper.startPage(1, 4);
        List<Goods> newGoods = goodsMapper.selectByExample(newGoodsExample);

        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(DESC);
        topicExample.createCriteria().andDeletedEqualTo(false);
        PageHelper.startPage(1, 4);
        List<Topic> topics = topicMapper.selectByExample(topicExample);

        WxHomeIndexVO vo = new WxHomeIndexVO();
        vo.setBanner(ads);
        vo.setBrandList(brands);
        vo.setChannel(categories);
        vo.setCouponList(coupons);
        vo.setFloorGoodsList(list);
        vo.setHotGoodsList(hots);
        vo.setNewGoodsList(newGoods);
        vo.setTopicList(topics);
        return vo;
    }
}
